<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\12\5 0005
 * Time: 15:18
 */

class MysqlModel
{

    const HOST_DSN = 'mysql:host=localhost;dbname=test';
    const HOST_USER = 'root';
    const HOST_PWD = 'root';


    private $client;

    public function __construct()
    {
        $this->client = new PDO(self::HOST_DSN, self::HOST_USER, self::HOST_PWD);
        $this->client->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->client->exec('set names utf8');
    }

    public function add($table, $field, $value, $bindParam)
    {
        $sql = "INSERT INTO `" .$table . "` (" . $field . ")VALUES (" . $value . ")";
        $stmt =  $this->client->prepare($sql);
        $stmt->execute($bindParam);
        $id = $this->client->lastinsertid();
        $this->client = null;
        return $id;
    }

    public function update($table, $set, $where, $bindParam)
    {
        $sql = "UPDATE " . $table . " SET " . $set . " WHERE " . $where;
        $stmt = $this->client->prepare($sql);
        $stmt->execute($bindParam);
        $rows = $stmt->rowCount();
        $this->client = null;
        return $rows;
    }

    public function select($table, $where, $bindParam)
    {
        $sql = "SELECT * FROM " . $table . " WHERE " . $where;
        $stmt = $this->client->prepare($sql);
        $stmt->execute($bindParam);
        $res =  $stmt->fetchAll(PDO::FETCH_ASSOC);
        $this->client = null;
        return $res;
    }

    public function delete($table, $where, $bindParam)
    {
        $sql = "DELETE FROM " . $table . " WHERE " . $where; //kevin%
        $stmt = $this->client->prepare($sql);
        $stmt->execute($bindParam);
        $rows = $stmt->rowCount();
        $this->client = null;
        return $rows;
    }
}